<!--
 * @Descripttion: 金牌话术
 * @Author: yansu
 * @Date: 2020-09-21 18:15:02
 * @LastEditors: yansu
 * @LastEditTime: 2020-11-24 00:18:00
-->
<template>
  <div class="wrap" v-loading='loading' >
    <el-card class="box-card" :class="{ setHeight: allowRecommend }">
      <div slot="header" class="clearfix">
        <span class="title">金牌话术导航<span v-if="history || !visible"  class="intelligentName" :title="intelligentName">{{intelligentName}}</span></span>
      </div>
      <div v-if="!history">
        <div v-if="visible && contentList.length">
          <div class="content">
            <div class="clearfix" v-for="(item, index) in contentList" :key="item.id" :class="{ highLight: currentIndex == index }" @click="select(item, index)">
              <span class="radio fl">
                <i></i>
              </span>
              <span class="session-name fr" :title="item.name">{{ item.name }}</span>
            </div>
          </div>
          <div class="btns">
            <el-button @click="preview">预览</el-button>
            <el-button type="primary" @click="using" v-if="showUseBtn">使用此话术</el-button>
          </div>
        </div>
        <div v-if="contentList.length == 0 && !loading" class="empty">
          <div class="imgWrap">
            <el-image :src="require('@/assets/img/intelligent/noIntelligent.png')" fit="fit">
            </el-image>
            <span>暂未配置金牌话术导航</span>
            </div>
        </div>
        <preview
          v-if="!visible && !usingFlag"
          @back="back"
          @useThis="using"
          :previewData="previewData"
          :showBtn = 'showUseBtn'
        />
        <using v-if="!visible && usingFlag " ref='using' :usingData="selectData" />
      </div>
      <!-- 历史 -->
    <history v-if="history" :reload='randomHistory' @history='getHistory'  ref="history"/>
    </el-card>
    <recommend v-if="allowRecommend" />
  </div>
</template>

<script>
import preview from "./components/preview";
import using from "./components/using";
import recommend from "./components/recommend";
import history from "./components/history";
import * as callType from "@/store/modules/call/mutation-types";
import { deepClone } from '@/utils/m7Utils.js'
export default {
  name:'intelligent',
  props: {
    reload: {type: Number, default: 0},
    refresh:String,
    randomCall:Number
  },
  components: {
    preview,
    using,
    recommend,
    history,
  },
  data() {
    return {
      currentIndex: 0,
      visible: true, //为true时展示话术列表，为false时可展示预览或使用话术
      usingFlag: false, //展示使用的话术
      showUseBtn: false, //是否展示使用话术按钮
      history: false,
      contentList: [],
      selectData: {},
      previewData:{},
      randomHistory:0,
      loading:true,
      historyName:''
    };
  },
  beforeMount() {
    console.log("beforeMount");
    console.log(this.cardList,'9999');
    this.getData()
  },
  activated(){
    if(this.tabType == 'cdr_outbound' || this.tabType == 'cdr_call'){
      this.getData()
    }
  },
  methods: {
    getData(){
      this.history = false;
      let params = {};
      let id = "";
      if (this.tabType == "cdr_call"){
        if(this.cdrCallList){
          this.cdrCallList.forEach((item) => {
            if (item.CALL_SHEET_ID == this.$route.params.id) {
              id = item.ERROR_MEMO ? item.ERROR_MEMO : "";
              if(item.saveIntelligentSpeach){
                this.selectData = item.saveIntelligentSpeach;
                this.visible = false;
                this.usingFlag = true;
                this.$nextTick(()=>{
                  //matchData是之前匹配过的话术，有可能是[]
                  this.$refs.using.match(item.matchData)
                })
                return
              }
            }
          });
        }
        params = {
          skillGroup: id,
        };
      } else if(this.tabType == 'cdr_outbound'){
        params = {};
        this.cardList.forEach(item=>{
          if(item.CALL_SHEET_ID == this.$route.params.id){
              if(item.saveIntelligentSpeach){
                this.selectData = item.saveIntelligentSpeach;
                this.visible = false;
                this.usingFlag = true;
                this.$nextTick(()=>{
                  //matchData是之前匹配过的话术，有可能是[]
                  this.$refs.using.match(item.matchData)
                })
                return
              }
          }
        })
      }else if(this.tabType == 'cdr_all'){
        this.history = true;
        this.loading = false;
        this.$nextTick(()=>{
          this.$refs.history.showHistory();
        })
        return
      }
      this.$store.dispatch("queryDiscourse", params).then((res) => {
        if (res.success) {
          this.contentList = res.data;
          this.loading = false;
        }
      });
    },
    getHistory(val){
      if(val){
        this.historyName = val.flow.name
      }else{
        this.historyName = ""
      }
    },
    select(val, idx) {
      console.log(val);
      this.currentIndex = idx;
      this.selectData = deepClone(val);
      this.previewData = deepClone(val);
    },
    preview() {
      //预览，不选择默认展示第一个
      this.visible = false;
      this.previewData =Object.keys(this.previewData).length > 0? this.previewData: this.contentList[0];
    },
    using() {
      //使用话术
      this.selectData = Object.keys(this.selectData).length > 0 ? this.selectData : this.contentList[0];
      let data = {
        _id:this.$route.params.id,
        data:this.selectData,
        tabType:this.tabType,
      }
      this.$store.commit("call/SAVE_CURRENT_SPEACH",data);
      window.sessionStorage.setItem('xRobotId',this.selectData.robot)
      let params = {
        callSheetId: this.$route.params.id,
        flowId: this.selectData.id,
        robot: this.selectData.robot,
      };
      this.$store.dispatch("adoptScriptFlow", params).then((res) => {
        if (res.success) {
          this.visible = false;
          this.usingFlag = true;
        }
      });
    },
    back() {
      this.visible = true;
    },
  },
  computed: {
    intelligentName(){
      let name = this.historyName || this.previewData.name || this.selectData.name
      return name? "(" + name + ")" : ""
    },
    refreshTab(){
      return this.refresh
    },
    routeId(){
      return this.$route.path.split('/')[4]
    },
    cardList() {
      // 获取卡片的list
      if (this.tabType && this.$route.path.split("/")[2] === "call") {
        if (this.$store.state.call && this.$store.state.call.callList) {
          if (this.$store.state.call.callList[this.tabType]) {
            let list =
              this.$store.state.call.callList[this.tabType].list || [];
            return JSON.parse(JSON.stringify(list));
          } else {
            return [];
          }
        } else {
          return [];
        }
      } else {
        return [];
      }
    },
    tabType(){
      //当前tab页
      return this.$route.path.split("/")[3]
    },
    allowRecommend() {
      //展示智能话术推荐列表
      if (this.tabType !== "cdr_pending" && this.tabType !== "cdr_all" && this.usingFlag )  {
        return true;
      } else {
        return false;
      }
    },
    isCalling() {
      //正在通话
      return this.$store.state.cti.globalLet.isCalling;
    },
    currentId() {
      //当前通话id
      return this.$store.state.cti.globalLet.currentCallSheetId;
    },
    cdrCallList() {
      //来电通话列表
      return this.$store.state.call.callList.cdr_call.list;
    },
  },
  watch: {
    refresh(val,val2){
      if(this.tabType == 'cdr_call'){
        if(val == 'goldenSession'){
          this.getData()
        }
      }
    },
    isCalling: {
      //挂断后不显示使用话术按钮
      handler: function (val) {
        if (val) {
          let callId = this.$store.state.cti.globalLet.currentCallSheetId
          if(callId && callId === this.routeId){
            this.showUseBtn = true;
          }else{
            this.showUseBtn = false;
          }
        }else{
          this.showUseBtn = false;
        }
      },
      immediate: true,
    },
    reload(val){
      if(this.tabType == 'cdr_all'){
        this.history = true;
        this.loading = false;
        this.$nextTick(()=>{
            this.$refs.history.showHistory()
        })
      }
    },
  },
};
</script>

<style lang="stylus" scoped>
.wrap {
  .box-card {
    margin:20px 20px 10px  20px;
    height: calc(100vh - 210px);
    /deep/.el-divider--horizontal {
        margin 10px 0
    }
    /deep/.el-card__body {
      padding 0px 20px
      position relative
      height:calc(100% - 60px)
      max-height: calc(100% - 60px);
      overflow-y: scroll;
      background white
    }
    .empty{
      display flex
      justify-content center
      align-items center
      position absolute
      top 0
      bottom 0
      left 0
      right 0
      margin auto
      .imgWrap{
        display flex
        align-items center
        span{
          margin 10px 0 0 10PX;
          color #B3B3B3;
        }
      }
    }
  }

  /deep/.setHeight {
    height: calc(75vh - 210px);
  }

  /deep/.el-card__header {
    background: #E9EBED;
    padding: 5px 20px;

    .title {
      font-size: 14px;
      font-weight: 600;
      display inline-block
      .intelligentName{
        margin-left 5px
        display inline-block
      }
    }
  }

  .content {
    margin: 20px auto;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;

    div {
      margin: 10px;
      height:40px;
      padding: 0 10px;
      line-height: 40px;
      font-size: 12px;
      border: 1px solid #E9EBED;
      border-radius: 5px;
      cursor: pointer;

      span {
        display: inline-block;
        &.radio {
           margin: 3px 6px 0 0px;
          i {
            display: inline-block;
            height: 15px;
            width: 15px;
            border: 1px solid #E9EBED;
            border-radius: 50%;
            box-sizing: border-box;
          }
        }
      }
      .session-name {
        width: 158px;
        text-overflow: ellipsis;
        overflow: hidden;
        display: inline-block;
        white-space: nowrap;
        line-height: 40px;
      }

      /deep/.el-radio__label {
        display: none;
      }

      &:hover {
        color: #4C97DB;
        border-color: #4C97DB;

        i {
          border-color: #4C97DB !important;
        }
      }

      &.highLight {
        color: #4C97DB;
        border-color: #4C97DB;

        i {
          width: 15px !important;
          height: 15px !important;
          border-width: 5px !important;
          border-color: #4C97DB !important;
          box-sizing: border-box;
        }
      }
    }
  }

  .btns {
    text-align: center;
    margin: 40px 15px;

    .el-button {
      line-height: 30px;
      margin: 0 15px;
      padding: 0 20px;
    }
  }
}
</style>
